const express = require('express');
const verifyToken = require('../middlewares/authMiddleware');
const router = express.Router();
const pool = require('../config/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { formatResponse } = require('../utils/response');

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const { username, password, email, mobile, age, gender } = req.body;
    
    const [emailCheck] = await pool.execute('SELECT id FROM users WHERE email = ?', [email]);
    if (emailCheck.length) {
      return res.status(400).json(formatResponse(400, '邮箱已注册'));
    }
    
    const [rows] = await pool.execute(
      'INSERT INTO users (username, email, password, mobile, gender, age, createdAt) VALUES (?, ?, ?, ?, ?, ?, NOW())',
      [username, email, await bcrypt.hash(password, 10), mobile, gender, age]
    );
    
    res.json(formatResponse(200, '注册成功', { userId: rows.insertId }));
  } catch (error) {
    res.status(500).json(formatResponse(500, '注册失败', error.message));
  }
});

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json(formatResponse(400, '用户名和密码不能为空'));
    }
    
    const [rows] = await pool.execute('SELECT * FROM users WHERE username = ?', [username]);
    if (!rows.length) {
      return res.status(404).json(formatResponse(404, '用户不存在'));
    }
    
    const user = rows[0];
    if (!(await bcrypt.compare(password, user.password))) {
      return res.status(401).json(formatResponse(401, '用户名或密码错误'));
    }
    
    const token = jwt.sign({ id: user.id }, 'your_secret_key', { expiresIn: '168h' });
    const { password: _, ...userInfo } = user; // 排除密码字段
    
    res.json(formatResponse(200, '登录成功', { token, user: userInfo }));
  } catch (error) {
    res.status(500).json(formatResponse(500, '登录失败', error.message));
  }
});

// 刷新token
router.post('/refresh-token', verifyToken, async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT * FROM users WHERE id = ?', [req.userId]);
    if (!rows.length) {
      return res.status(404).json(formatResponse(404, '用户不存在'));
    }
    
    const token = jwt.sign({ id: req.userId }, 'your_secret_key', { expiresIn: '168h' });
    res.json(formatResponse(200, 'Token刷新成功', { token }));
  } catch (error) {
    res.status(500).json(formatResponse(500, 'Token刷新失败', error.message));
  }
});

module.exports = router;